import os
from werkzeug.utils import secure_filename
from flask import current_app, render_template, request,abort,send_from_directory,g,flash,redirect, url_for
from . import file_bp
from formodle import Uploadmd,Uploadimgmd
from getpath import Getpath
from decoraters import isloginin,isrgroup
from models import Userinfo
from exts import db
from toolfunc import flash_form_error

@file_bp.route('/upload',methods=["GET","POST"])
@isrgroup(2) 
@isloginin
def upload():
    form=Uploadmd()
    if request.method=="GET":
        return render_template("upload.html",form=form)
    if request.method=="POST":
        if form.validate_on_submit():
            f=request.files['ftmp']
            f.save(os.path.join(current_app.config["BASE_DIR"],current_app.config["UPLOAD_FOLDER"],secure_filename(f.filename)))
            flash("压缩包上传成功")
        else:
            flash_form_error(form=form)
        return redirect(url_for("file.upload"))
    else:
        abort(404)

def rename_file(filename,newname):
    ext = os.path.splitext(filename)[1]
    new_filename = newname + ext
    return new_filename


@file_bp.route('/download')
@isrgroup(1)
@isloginin
def download():
    fdf=os.path.join(current_app.config['BASE_DIR'],current_app.config['DOWNLOAD_FOLDER'])
    fdict=Getpath.getfile_dict(fdf)
    return render_template('download.html',fdict=fdict)

@file_bp.route('/download_<int:fid>')
@isloginin
def downloadfile(fid):
    fdf=os.path.join(current_app.config['BASE_DIR'],current_app.config['DOWNLOAD_FOLDER'])
    fdict=Getpath.getfile_dict(fdf)
    return send_from_directory(fdict[fid][0],fdict[fid][1],as_attachment=True)


@file_bp.route('/uploadimg',methods=["GET","POST"])
@isloginin
def uploadimg():
    form=Uploadimgmd()
    if request.method=="GET":
        return render_template("uploadimg.html",form=form)
    if request.method=="POST":
        if form.validate_on_submit():
            f=request.files['ftmp']
            newname=rename_file(f.filename,str(g.uid))
            f.save(os.path.join(current_app.config["BASE_DIR"],current_app.config["UPLOAD_IMG_FOLDER"],newname))
            user=Userinfo.query.filter(Userinfo.u_id==g.uid).first()
            user.u_img=current_app.config["BASE_IMG_URL"]+newname
            db.session.commit()
            flash("头像上传成功！刷新以显示")
        else:
            flash_form_error(form=form)
        return redirect(url_for("file.uploadimg"))
    else:
        abort(404)